package com.pharmacy.UserManage.controller;

import com.pharmacy.UserManage.entity.User;
import com.pharmacy.UserManage.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    // 用户登录
    @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> login(@RequestParam String username,
                                                     @RequestParam String password,
                                                     HttpSession session) {
        Map<String, Object> response = new HashMap<>();

        User user = userService.login(username, password);
        if (user != null) {
            session.setAttribute("currentUser", user);
            response.put("success", true);
            response.put("message", "登录成功");
            response.put("data", user);
            return ResponseEntity.ok(response);
        } else {
            response.put("success", false);
            response.put("message", "用户名或密码错误");
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 用户注销
    @PostMapping("/logout")
    public ResponseEntity<Map<String, Object>> logout(HttpSession session) {
        session.invalidate();
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "注销成功");
        return ResponseEntity.ok(response);
    }

    // 获取当前用户信息
    @GetMapping("/current")
    public ResponseEntity<Map<String, Object>> getCurrentUser(HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        User currentUser = (User) session.getAttribute("currentUser");

        if (currentUser != null) {
            response.put("success", true);
            response.put("data", currentUser);
        } else {
            response.put("success", false);
            response.put("message", "用户未登录");
        }
        return ResponseEntity.ok(response);
    }

    // 获取所有用户（仅管理员）
    @GetMapping("/list")
    public ResponseEntity<Map<String, Object>> getAllUsers(HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        User currentUser = (User) session.getAttribute("currentUser");

        // 权限检查
        if (currentUser == null || !"admin".equals(currentUser.getRole())) {
            response.put("success", false);
            response.put("message", "权限不足");
            return ResponseEntity.status(403).body(response);
        }

        List<User> users = userService.getAllUsers();
        response.put("success", true);
        response.put("data", users);
        return ResponseEntity.ok(response);
    }

    // 根据ID获取用户（仅管理员）
    @GetMapping("/{id}")
    public ResponseEntity<Map<String, Object>> getUserById(@PathVariable Integer id, HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        User currentUser = (User) session.getAttribute("currentUser");

        // 权限检查
        if (currentUser == null || !"admin".equals(currentUser.getRole())) {
            response.put("success", false);
            response.put("message", "权限不足");
            return ResponseEntity.status(403).body(response);
        }

        User user = userService.getUserById(id);
        if (user != null) {
            response.put("success", true);
            response.put("data", user);
            return ResponseEntity.ok(response);
        } else {
            response.put("success", false);
            response.put("message", "用户不存在");
            return ResponseEntity.notFound().build();
        }
    }

    // 添加用户（仅管理员）
    @PostMapping("/add")
    public ResponseEntity<Map<String, Object>> addUser(@RequestBody User user, HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        User currentUser = (User) session.getAttribute("currentUser");

        // 权限检查
        if (currentUser == null || !"admin".equals(currentUser.getRole())) {
            response.put("success", false);
            response.put("message", "权限不足");
            return ResponseEntity.status(403).body(response);
        }

        if (userService.addUser(user)) {
            response.put("success", true);
            response.put("message", "用户添加成功");
            return ResponseEntity.ok(response);
        } else {
            response.put("success", false);
            response.put("message", "用户名已存在");
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 更新用户（仅管理员）
    @PutMapping("/update")
    public ResponseEntity<Map<String, Object>> updateUser(@RequestBody User user, HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        User currentUser = (User) session.getAttribute("currentUser");

        // 权限检查
        if (currentUser == null || !"admin".equals(currentUser.getRole())) {
            response.put("success", false);
            response.put("message", "权限不足");
            return ResponseEntity.status(403).body(response);
        }

        if (userService.updateUser(user)) {
            response.put("success", true);
            response.put("message", "用户更新成功");
            return ResponseEntity.ok(response);
        } else {
            response.put("success", false);
            response.put("message", "用户名已存在或更新失败");
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 删除用户（仅管理员）
    @DeleteMapping("/delete/{id}")
    public ResponseEntity<Map<String, Object>> deleteUser(@PathVariable Integer id, HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        User currentUser = (User) session.getAttribute("currentUser");

        // 权限检查
        if (currentUser == null || !"admin".equals(currentUser.getRole())) {
            response.put("success", false);
            response.put("message", "权限不足");
            return ResponseEntity.status(403).body(response);
        }

        if (userService.deleteUser(id)) {
            response.put("success", true);
            response.put("message", "用户删除成功");
            return ResponseEntity.ok(response);
        } else {
            response.put("success", false);
            response.put("message", "用户删除失败");
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 根据角色获取用户（仅管理员）
    @GetMapping("/role/{role}")
    public ResponseEntity<Map<String, Object>> getUsersByRole(@PathVariable String role, HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        User currentUser = (User) session.getAttribute("currentUser");

        // 权限检查
        if (currentUser == null || !"admin".equals(currentUser.getRole())) {
            response.put("success", false);
            response.put("message", "权限不足");
            return ResponseEntity.status(403).body(response);
        }

        List<User> users = userService.getUsersByRole(role);
        response.put("success", true);
        response.put("data", users);
        return ResponseEntity.ok(response);
    }

    // 检查用户名是否存在
    @GetMapping("/checkUsername")
    public ResponseEntity<Map<String, Object>> checkUsername(@RequestParam String username) {
        Map<String, Object> response = new HashMap<>();
        boolean exists = userService.isUsernameExist(username);
        response.put("success", true);
        response.put("exists", exists);
        return ResponseEntity.ok(response);
    }
//
// 获取当前用户详细信息
@GetMapping("/profile")
public ResponseEntity<Map<String, Object>> getProfile(HttpSession session) {
    Map<String, Object> response = new HashMap<>();
    User currentUser = (User) session.getAttribute("currentUser");

    if (currentUser != null) {
        // 重新从数据库获取最新信息
        User user = userService.getUserById(currentUser.getId());
        response.put("success", true);
        response.put("data", user);
        return ResponseEntity.ok(response);
    } else {
        response.put("success", false);
        response.put("message", "用户未登录");
        return ResponseEntity.status(401).body(response);
    }
}

    // 更新个人信息
    @PutMapping("/updateProfile")
    public ResponseEntity<Map<String, Object>> updateProfile(@RequestBody Map<String, Object> updateData, HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        User currentUser = (User) session.getAttribute("currentUser");

        if (currentUser == null) {
            response.put("success", false);
            response.put("message", "用户未登录");
            return ResponseEntity.status(401).body(response);
        }

        try {
            // 获取要更新的用户
            User user = userService.getUserById(currentUser.getId());

            // 更新用户名
            if (updateData.containsKey("username")) {
                String newUsername = (String) updateData.get("username");

                // 检查用户名是否已存在（排除当前用户）
                User existingUser = userService.findByUsername(newUsername);
                if (existingUser != null && !existingUser.getId().equals(user.getId())) {
                    response.put("success", false);
                    response.put("message", "用户名已存在");
                    return ResponseEntity.badRequest().body(response);
                }
                user.setUsername(newUsername);
            }

            // 更新密码（如果需要）
            if (updateData.containsKey("oldPassword") && updateData.containsKey("newPassword")) {
                String oldPassword = (String) updateData.get("oldPassword");
                String newPassword = (String) updateData.get("newPassword");

                // 验证原密码
                if (!user.getPassword().equals(oldPassword)) {
                    response.put("success", false);
                    response.put("message", "原密码不正确");
                    return ResponseEntity.badRequest().body(response);
                }

                // 更新密码
                user.setPassword(newPassword);
            }

            // 保存更新
            boolean success = userService.updateUser(user);
            if (success) {
                // 更新session中的用户信息
                session.setAttribute("currentUser", user);

                response.put("success", true);
                response.put("message", "个人信息更新成功");
                response.put("data", user);
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "更新失败");
                return ResponseEntity.badRequest().body(response);
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "更新过程中发生错误");
            return ResponseEntity.status(500).body(response);
        }
    }
}
